package com.mf.page;

import java.util.Set;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.mf.MyApplication;
import com.mf.R;
import com.mf.mpos.pub.Controler;
import com.mf.mpos.pub.result.*;
import com.mf.mpos.util.Misc;

public class BluetoothSetPage extends Activity {
	
	private ListView mListView;
	private BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
	private BluetoothListAdapter mAdapter;
	private Button openBtn;
	private Button saveBtn;
	private ProgressDialog waitDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bluetoothset);
		
		mAdapter = new BluetoothListAdapter(this);
		mListView = (ListView) findViewById(R.id.listview);
		mListView.setAdapter(mAdapter);
		mListView.setFastScrollEnabled(true);
		mListView.setOnItemClickListener(mListClickListener);
		
		openBtn = (Button) findViewById(R.id.openBtn);
		openBtn.setOnClickListener(openListener);
		saveBtn = (Button) findViewById(R.id.saveBtn);
		saveBtn.setOnClickListener(saveListener);
		
		Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
		//如果系统中已匹配的蓝牙数为0，则打开蓝牙设置界面；否则先显示蓝牙匹配列表
		if(pairedDevices.size() > 0){
			refeshList();
		}
		else{
			//开启系统蓝牙设置界面
			openSystemBluetoothPage();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//从系统蓝牙设置界面返回后，刷新匹配列表
		refeshList();
	}
	
	private OnItemClickListener mListClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int position, long id) {
        	//列表框选中处理
        	mAdapter.setSelected(position);
        }
	};
	
	Button.OnClickListener openListener = new Button.OnClickListener(){
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			openSystemBluetoothPage();
		}
	};
	
	Button.OnClickListener saveListener = new Button.OnClickListener(){
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if(mAdapter.getSelected() >= 0)
			{
				//创建等待窗口
				waitDialog = ProgressDialog.show(BluetoothSetPage.this, "正在连接蓝牙", "请稍等。。。", true);
				
				// 开启一个新线程，在新线程里执行连接蓝牙这个有可能耗时的操作
				new Thread(new Runnable() {  
					@Override  
					public void run() {  
						//断开原来的连接
						if(Controler.posConnected())
						{
							Controler.disconnectPos();
						}
						
						Log.v("uninpay", "--setAddress:" + ((BluetoothItem)mAdapter.getItem(mAdapter.getSelected())).getAddress());
						//连接
						String mac = ((BluetoothItem)mAdapter.getItem(mAdapter.getSelected())).getAddress();
						Controler.connectPos(mac);
						// 等待完毕后发送消息关闭进度框
						handler.sendEmptyMessage(0);
					}   
				}).start(); 
			}
			else
			{
				Toast.makeText(MyApplication.getInstance(), "请选择要连接的蓝牙", Toast.LENGTH_LONG).show();
			}
		}
	};
	
	Handler handler = new Handler() {  
		@Override  
		public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法  
			// 关闭ProgressDialog  
			waitDialog.dismiss();
			//根据最终连接状态判断
			if(Controler.posConnected())
			{		
				IPageCallback btnProc = (IPageCallback)getIntent().getExtras().getSerializable("pageCallback");

				if(btnProc != null)
				{	
					btnProc.SetExitReason(IPageCallback.OK);
				}
				
				finish();
			}
			else
			{
				Toast.makeText(MyApplication.getInstance(), "连接失败，请重试", Toast.LENGTH_LONG).show();
			}
		}  
	};  
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		IPageCallback btnProc = (IPageCallback)getIntent().getExtras().getSerializable("pageCallback");

		if(btnProc != null)
		{	
			btnProc.SetExitReason(IPageCallback.CANCEL);
		}
		
		finish();
	}

	
	//打开系统蓝牙设置界面
	protected void openSystemBluetoothPage()
	{
		Intent intent = new Intent();
		intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
		startActivityForResult(intent,0);
	}
	
	//刷新已匹配到的蓝牙列表界面
	protected void refeshList()
	{
		Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
		
		 mAdapter.clear();
		 for (BluetoothDevice device : pairedDevices) {
			 mAdapter.addItem(new BluetoothItem(device.getName(),device.getAddress(), false));
        }
		 mAdapter.notifyDataSetChanged();
		 mListView.setSelection(mAdapter.getCount() - 1);
	}
}
